/*
 * TepcoMeter:HttpUtils.java
 * Copyright © 2011 ho9ho9 All Rights Reserved.
 */
package com.ho9ho9.tepcometer.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.util.Log;

/**
 * Http通信を取り扱う汎用クラス.
 * @author ho9ho9
 */
public class HttpUtils {
	
	/** HTTP_METHOD_GET. */
	private static final String HTTP_METHOD_GET = "GET";

	private HttpUtils() {
	}
	
	private static final String TAG_NAME = "TepcoMetterWidgetService";
	
	/**
	 * URLに対してGETでHTTPリクエストを送ります.
	 * @param url URL
	 * @return null:例外発生 null以外：レスポンス
	 */
	public static String get(String url) {
		Log.d(TAG_NAME, "url:" + url);
		return request(url, HTTP_METHOD_GET);
	}
	
	/**
	 * URLに対してHTTPリクエストを送ります.
	 * @param url URL
	 * @param method HTTP Method
	 * @return null:例外発生 null以外：レスポンス
	 */
	private static String request(String url, String method) {
		String result = null;
		HttpURLConnection con = null;
		BufferedReader reader = null;
		try {
			// コネクション接続
			con = (HttpURLConnection) new URL(url).openConnection();
			con.setRequestMethod(method);
			// 読み込み開始
			reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			result = sb.toString();
		} catch (MalformedURLException e) {
			Log.e(TAG_NAME, e.getMessage(), e);
		} catch (IOException e) {
			Log.e(TAG_NAME, e.getMessage(), e);
		} finally {
			if (con != null) {
				con.disconnect();
			}
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
			}
		}
		Log.d(TAG_NAME, "response:" + result);
		return result;
	}

}
